const cloud = require('wx-server-sdk')

cloud.init()

const SUCCESS = 0;
const BAD_PARAM = -1;

exports.main = async (event) => {
  const db = cloud.database();
  const content = event.content;

  if (content == null) {
    return {
      code: BAD_PARAM,
      result: content
    };
  }

  try {
    const parsedContent = JSON.parse(content);

    if (!parsedContent.hasOwnProperty('lastRevisionTime')) {
      parsedContent['lastRevisionTime'] = Date.now();
    }

    if (typeof parsedContent['body'] == 'string') {
      // rectify
      parsedContent['body'] = [
        {'type': 'text', 'value': parsedContent['body']}
      ]
    }

    await db.collection('articles').add({
      data: parsedContent
    });
    return {
      code: SUCCESS,
      result: {
        content: content,
        parsedContent: parsedContent
      }
    };
  } catch (e) {
    return {
      code: BAD_PARAM,
      result: JSON.stringify(e)
    };
  }
}
